package top.zxybird.demo.jcp.c16;

/**
 * Created by zxybird on 2018/2/22.
 */
public class PossibleRecordering {

  private int x = 0, y = 0;
  private int a = 0, b = 0;

  public static void main(String[] args) throws InterruptedException {

    PossibleRecordering obj = new PossibleRecordering();

    int i = 0;
    for (;;) {
      i++;
      obj.x = 0;
      obj.y = 0;
      obj.a = 0;
      obj.b = 0;
      Thread one = new Thread(() -> {
        // 由于线程one先启动，下面这句话让它等一等线程two. 读着可根据自己电脑的实际性能适当调整等待时间.
        shortWait(100000);
        obj.a = 1;
        obj.x = obj.b;
      });

      Thread other = new Thread(() -> {
        obj.b = 1;
        obj.y = obj.a;
      });
      one.start();
      other.start();
      one.join();
      other.join();
      String result = "第" + i + "次 (" + obj.x + "," + obj.y + "）";
      if (obj.x == 0 && obj.y == 0) {
        System.err.println(result);
        break;
      } else {
        System.out.println(result);
      }
    }
  }

  public static void shortWait(long interval) {
    long start = System.nanoTime();
    long end;
    do {
      end = System.nanoTime();
    } while (start + interval >= end);
  }
}
